package com.ybg.share.core.report;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.type.AnnotationMetadata;

import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;

/**
 * 手动扫描注册Bean 到Spring Context中，在jndimap.properties 配置文件中加入自己的JNDI即可。
 * 使用@Import(SpringBootJNDIBuildinDatasource.class) 再springboot启动类头部加上即可
 * @author  deament
 */
public class SpringBootJNDIBuildinDatasource implements ImportBeanDefinitionRegistrar {
    Logger logger= LoggerFactory .getLogger(SpringBootJNDIBuildinDatasource.class);
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        ClassPathResource resource= new ClassPathResource("jndimap.properties");
        EncodedResource encodedResource= new EncodedResource(resource,"UTF-8");
        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(encodedResource);
            Iterator<Object> iterator = properties.keySet().iterator();
            int count=1;
            while (iterator.hasNext()){
                            BeanDefinitionBuilder builder= BeanDefinitionBuilder.genericBeanDefinition(JNDIBuildinDatasource.class);
                String key=iterator.next().toString();
                if(key.length()==0){
                   continue;
                }
                builder.addPropertyValue("name",key);
                builder.addPropertyValue("jndiName", properties.get(key).toString());
                BeanDefinition beanDefinition=builder.getBeanDefinition();
                beanDefinitionRegistry.registerBeanDefinition("jNDIBuildinDatasource"+count,beanDefinition);
                logger.info("key="+key+",BeanName="+"jNDIBuildinDatasource"+count);
                count++;
            }

        } catch (IOException e) {
            e.printStackTrace();
            logger.info("jndimap.properties is not find");
            return ;
        }



    }
}
